package com.view.mediator
{
	import com.model.proxy.ComponentStateProxy;
	import com.view.component.FourView;

	import flash.events.Event;

	import org.puremvc.as3.multicore.interfaces.IMediator;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class FourViewMediator extends Mediator implements IMediator
	{
		public static const NAME:String='FourViewMediator';
		private var componentStateProxy:ComponentStateProxy;

		public function FourViewMediator(viewComponent:Object)
		{
			super(NAME, viewComponent);
		}

		protected function get fourView():FourView
		{
			return viewComponent as FourView;
		}

		override public function onRegister():void
		{
			componentStateProxy=facade.retrieveProxy(ComponentStateProxy.NAME) as ComponentStateProxy;
			fourView.addEventListener(FourView.STATE_CREATED, onStateCreated);
			fourView.labelText=NAME + " wrote this.";
			fourView.currentState=componentStateProxy.switchTo;
			checkForMediator(fourView.activeView);
		}

		override public function listNotificationInterests():Array
		{
			return [MainViewMediator.STATES_SWITCHER];
		}

		override public function handleNotification(note:INotification):void
		{
			switch (note.getName())
			{
				case MainViewMediator.STATES_SWITCHER:
					componentStateProxy=facade.retrieveProxy(ComponentStateProxy.NAME) as ComponentStateProxy;
					fourView.currentState=componentStateProxy.switchTo;
					break;
			}
		}

		protected function onStateCreated(event:Event):void
		{
			checkForMediator(fourView.activeView);
		}

		protected function checkForMediator(child:Object):void
		{
			fourView.visitedViews++;
			switch (child.id)
			{
				case "StateOneView":
					if (!facade.hasMediator(StateOneViewMediator.NAME))
						facade.registerMediator(new StateOneViewMediator(child));
					break;
				case "StateTwoView":
					if (!facade.hasMediator(StateTwoViewMediator.NAME))
						facade.registerMediator(new StateTwoViewMediator(child));
					break;
			}
			if (fourView.visitedViews == fourView.numberOfViews)
			{
				fourView.removeEventListener(FourView.STATE_CREATED, onStateCreated);
			}
		}
	}
}